
import { ajax } from '../../ajax'
import { Page } from '/utils/ix' // 添加这行
import { conpanyUrl } from '/public/static';
import { imgUrl } from '/public/static';
var getSocket = require("/utils/utilsIndex.js");

Page({
  data: {
    token: '',
    totalAmount: '',
    out_trade_no: '',
    background: [],
    indicatorDots: false,
    autoplay: true,
    interval: 3000,
    circular: true,
    acceleration: true,
    disable_touch: true,
    imgUrl: imgUrl,
    bgStatus: '',
    deviceNumber: '',
    client_id: ''
  },

  // 键盘监听
  onKeyPress(r) {
    switch (r.keyCode) {
      case 131:
        r.keyName = '收款';
        this.setData({ totalAmount: r.amount })
        break;
      case 132:
        r.keyName = '刷脸';
        console.log('刷脸')
        break;
      case 133:
        r.keyName = '取消';
        console.log('取消')
        break;
      case 134:
        r.keyName = '设置';
        console.log('设置')
        my.navigateTo({ url: "/pages/setting/water-record/water-record" });
        break;
    }
    console.log('KeyEvent', r);
  },
  // onGetAuthorize(res) {
  //   console.log(res);
  //   my.getPhoneNumber({
  //     success: (res) => {
  //       console.log(res);
  //       let encryptedData = res.response;
  //       // my.request({
  //       //   url: '你的后端服务端',
  //       //   data: encryptedData,
  //       // });
  //     },
  //     fail: (res) => {
  //       console.log(res);
  //       console.log('getPhoneNumber_fail');
  //     },
  //   });
  // },
  // 首页轮播图
  async getImages() {
    let imgData = await ajax('/getSmallImg', { token: this.data.token });
    if (imgData.data.code === 10001) {
      this.setData({ background: imgData.data.data })
    } else {
      this.setData({ bgStatus: 1 })
    }
  },

  // 普通支付
  async facePay(touchStyle) {
    let totalAmount = this.data.totalAmount;
    // 支付金额清0，否则按下支付btn会直接调起收银台，因为有原来的this.data.totalAmount
    this.setData({ totalAmount: 0 })
    if (totalAmount > 0 && touchStyle === 2 && this.data.token) {
      console.log('创建订单')
      //创建订单
      let createOrderData = await ajax("/SmallAppSmilePreform", { token: this.data.token, amount: totalAmount }, 'POST');
      console.log(createOrderData);
      if (createOrderData.data.status === 1) {
        console.log('进来了');
        this.setData({ out_trade_no: createOrderData.data.out_trade_no });
        //启动收银台
        my.ix.startApp({
          appName: 'cashier',
          bizNo: createOrderData.data.out_trade_no,
          totalAmount: totalAmount,
          orderDetail: [{ name: '支付', content: '普通商品' }],
          showScanPayResult: false,
          success: async (r) => {
            let parameData = {
              code: r.barCode,
              token: this.data.token,
              out_trade_no: this.data.out_trade_no,
              devices: my.getStorageSync({ key: 'system' }).data,
              ftoken: r.ftoken
            }
            console.log(parameData)
            //支付接口
            let payResultData = await ajax("/SmallAppSmilePay", parameData, 'POST');
            console.log(payResultData)
            //暂时关闭自定义结果页
            // my.navigateTo({url: '../pay-result/pay-result?out_trade_no='+ this.data.out_trade_no + '&result_status=1'});
            if (payResultData.data.status === 1) {
              console.log('支付成功了。。。')
              // 支付成功后给后屏发送支付成功信息
              my.ix.sendBuddyMessage({
                target: "2019120369640398",
                data: {
                  pay_status: true,
                },
                success: (res) => {
                  console.log('发送成功', res)
                },
                fail: (res) => { }
              })
              // 请求打印数据并打印
              this.getData()
              // this.onKeyPress(r)
              my.ix.startApp({
                appName: 'scanPayResult',
                bizNo: this.data.out_trade_no,
                totalAmount: totalAmount,
                success: (r) => {
                  console.log('展示结果页')
                }
              })
            }
          }
        })
      }
    } else {
      my.ix.speech({
        text: '请输入金额',
        success: (r) => {
          console.log('请输入金额')
        }
      });
    }
    console.log('aaa')
  },

  // 押金扫码支付
  async fundauthPay(touchStyle) {
    let totalAmount = this.data.totalAmount;
    this.setData({ totalAmount: 0 })
    if (totalAmount > 0 && touchStyle === 2 && this.data.token) {
      //创建订单
      let createOrderData = await ajax("/SmallAppSmileFundauthPreform", { token: this.data.token, amount: totalAmount }, 'POST');
      if (createOrderData.data.status === 1) {
        console.log('进来了');
        this.setData({ out_trade_no: createOrderData.data.out_trade_no });
        //启动收银台
        my.ix.startApp({
          appName: 'cashier',
          bizNo: createOrderData.data.out_trade_no,
          totalAmount: totalAmount,
          orderDetail: [{ name: '支付', content: '普通商品' }],
          showScanPayResult: true,
          success: async (r) => {
            let parameData = {
              code: r.barCode,
              token: this.data.token,
              out_trade_no: this.data.out_trade_no,
              devices: my.getStorageSync({ key: 'system' }).data,
              ftoken: r.ftoken
            }
            console.log('parameData', parameData)
            //支付接口
            let payResultData = await ajax("/SmallAppSmileFundauth", parameData, 'POST');
            console.log(payResultData)

            //暂时关闭自定义结果页
            my.navigateTo({ url: '../pay-result/pay-result?out_trade_no=' + this.data.out_trade_no + '&result_status=2' });

            if (payResultData.data.status === 1) {
              console.log('支付成功了。。。')
              // 请求打印数据并打印
              this.getData()
              // this.onKeyPress(r)
              my.ix.startApp({
                appName: 'scanPayResult',
                bizNo: this.data.out_trade_no,
                totalAmount: totalAmount,
                success: (r) => {
                  console.log('展示结果页')
                }
              })
            } else {
              my.alert({
                content: payResultData.data.msg
              });
            }
          }
        })
      }
    } else {
      // 语音功能
      my.ix.speech({
        text: '输入金额有误',
        success: (r) => {
          console.log('输入金额有误')
        }
      });
    }
    console.log('aaa')
  },
  // 刷脸预授权
  async sFace() {
    let totalAmount = this.data.totalAmount;
    this.setData({
      totalAmount: 0
    })
    console.log(totalAmount)
    let createOrderData = await ajax("/SmallAppSmileFundauthPreform", { token: this.data.token, amount: totalAmount }, 'POST');
    if (createOrderData.data.status === 1) {
      console.log('进来了');
      this.setData({ out_trade_no: createOrderData.data.out_trade_no });
      // 刷脸核身
      my.ix.faceVerify({
        verifyType: 'idCard',
        option: 'pay',
        needPreAuth: 'true',
        success: async (res) => {
          let ftoken = res.ftoken;
          let parameData = {
            code: ftoken,
            token: this.data.token,
            out_trade_no: this.data.out_trade_no,
            deviceType: 'alipay',
            devices: my.getStorageSync({ key: 'system' }).data
          }
          let payResultData = await ajax("/SmallAppSmileFundauth", parameData, 'POST');
          console.log(payResultData)
          if (payResultData.data.status === 1) {
            //暂时关闭自定义结果页
            console.log('暂时关闭自定义结果页', this.data.out_trade_no, payResultData.data.out_order_no)
            // 预授权订单页result_status=2
            my.navigateTo({ url: '../pay-result/pay-result?out_trade_no=' + payResultData.data.out_order_no + '&result_status=2' });
          }
        }
      })
    }
  },

  // 普通支付
  basic_pay() {
    console.log('普通支付')
    this.facePay(2)
  },

  // 押金扫码支付
  deposit_scan_pay() {
    console.log('押金扫码支付')
    this.fundauthPay(2)
  },

  // 押金刷脸支付
  deposit_face_pay() {
    console.log('押金刷脸支付')
    this.sFace(2);
  },

  // 注销页
  logout() {
    my.navigateTo({ url: '../logout/logout' });

  },

  // 获取打印信息
  getData() {
    let token = my.getStorageSync({ key: 'token' }).data;
    ajax('/SmallAppSmilePayQuery', { token, out_trade_no: this.data.out_trade_no }).then((res) => {
      console.log(res)
      if (res.data.data.print) {
        this.printer(res.data.data.print)
      }
    })
  },

  // 打印内容
  printer(data) {
    let { PayWays, cashier_name, out_trade_no, pay_status, print_time, qr_code, remark, store_name, total_amount, trade_no, updated_at } = data;
    //查询打印机连接状态
    my.ix.printerStatus({
      success: (r) => {
        my.ix.printer({
          cmds: [
            { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'ON'] },
            { 'cmd': 'addSelectJustification', 'args': ['CENTER'] },
            { 'cmd': 'addText', 'args': [store_name] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            // {'cmd':'addText', 'args':['']},
            // {'cmd':'addPrintAndLineFeed', 'args':[]},
            { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'OFF', 'OFF', 'OFF'] },
            { 'cmd': 'addSelectJustification', 'args': ['CENTER'] },
            { 'cmd': 'addTurnDoubleStrikeOnOrOff', 'args': ['ON'] },
            { 'cmd': 'addText', 'args': [store_name] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] }, //9
            // {'cmd':'addPrintAndFeedLines', 'args':['1']},
            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addTurnDoubleStrikeOnOrOff', 'args': ['OFF'] },
            { 'cmd': 'addText', 'args': ['支付方式：'] },
            { 'cmd': 'addText', 'args': [PayWays === 'alipay' ? '支付宝收款' : '微信收款'] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['订单类型：'] },
            { 'cmd': 'addText', 'args': [pay_status === 1 ? '收款' : '退款'] }, //15
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['交易时间：' + updated_at] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] }, //20

            { 'cmd': 'addText', 'args': ['==============================='] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['订单号：' + out_trade_no] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['流水号：'] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addText', 'args': [trade_no] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['==============================='] }, //30
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['收款：'] },
            { 'cmd': 'addText', 'args': ['￥' + total_amount] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['备注：' + remark] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['==============================='] }, //40
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addSelectJustification', 'args': ['CENTER'] }, /*设置打印居中对齐*/
            { 'cmd': 'addStoreQRCodeDataGB18030', 'args': [out_trade_no] }, /*设置qrcode内容*/
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addSelectJustification', 'args': ['LEFT'] },
            { 'cmd': 'addText', 'args': ['==============================='] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addText', 'args': ['收银员：' + cashier_name] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addText', 'args': ['打印时间：' + print_time] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addText', 'args': [''] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addSelectJustification', 'args': ['CENTER'] },
            { 'cmd': 'addText', 'args': ['天择可付 智慧收银'] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addText', 'args': [''] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },

            { 'cmd': 'addSelectPrintModes', 'args': ['FONTA', 'OFF', 'ON', 'ON', 'OFF'] },
            { 'cmd': 'addText', 'args': ['小票编号：0503-1'] },
            { 'cmd': 'addPrintAndLineFeed', 'args': [] },
            { 'cmd': 'addPrintAndFeedLines', 'args': ['1'] },
          ],
          success: (r) => {
            console.log("success");
          },
          fail: (r) => {
            console.log("fail, errorCode:" + r.error);
          }
        });
      },
      fail: (r) => {
        // my.showToast({content: '打印机未连接'})
      }
    });
  },

  onLoad(option) {
    // console.log(option)
    // 商户未登录，跳转登录页
    let that = this;
    // 获取设备号
    let r = my.ix.getSysPropSync({ key: 'ro.serialno' });
    if (r) {
      my.setStorageSync({ key: 'system', data: r.value });
    }
    let token = my.getStorageSync({ key: 'token' }).data;
    // console.log(token)
    // 设置token过期，测试用
    // let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vcGF5LnRpYXplLmNvbS9hcGkvbWVyY2hhbnQvbG9naW4iLCJpYXQiOjE1NTIwMDczNzQsImV4cCI6MTU1MjYxMjE3NCwibmJmIjoxNTUyMDA3Mzc0LCJqdGkiOiJlNjExNDI4MjUwODEzOWE0MjlhYTg2NDc3ZGMxNGZkNCIsInN1YiI6eyJpZCI6MTIsIm5hbWUiOiJcdTU5MjlcdTYyZTlcdTRmZTFcdTRlMGFcdTYyODBcdTY3MmZcdTkwZTgiLCJwaG9uZSI6IjE3NTAwMDAxODAwIiwidHlwZSI6Im1lcmNoYW50IiwibWVyY2hhbnRfdHlwZSI6MCwicGlkIjowLCJpbWVpIjpudWxsfX0.g3Dy2qNiK1EA5cT1_ht0wAdwVBoA0VbxHR2kb0cePtk';
    if (token) {
      that.setData({ token })
    } else {
      my.reLaunch({ url: '../login/login' })
    }
    //获取轮播图
    that.getImages()
  },
  onShow() {
    let that = this;
    console.log('show')
    // 接收后屏发送的信息
    my.ix.onBuddyMessage({
      success: (res) => {
        console.log('接受信息', res)
        if (res.payFinish === true) {
          console.log('接受信息true')
          that.setData({ totalAmount: res.totalAmount })
          that.basic_pay()
        }
      }
    })
  

  },

  onHide() {

  }

});
